﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rapattern.Utilities
{
    public class XmlSerializerHelper
    {
        /// <summary>
        /// 保存对象到xml文件中
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool SaveToXml(string filePath, object obj)
        {
            if (!string.IsNullOrWhiteSpace(filePath) && obj != null)
            {
                if (!Directory.Exists(Path.GetDirectoryName(filePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                }
                using (StreamWriter writer = new StreamWriter(filePath, false))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer =
                        new System.Xml.Serialization.XmlSerializer(obj.GetType());
                    xmlSerializer.Serialize(writer, obj);
                }
            }
            else
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 把xml映射到对象中
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object LoadFromXml(string filePath, Type type)
        {
            object result = null;

            if (File.Exists(filePath))
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer =
                        new System.Xml.Serialization.XmlSerializer(type);
                    result = xmlSerializer.Deserialize(reader);
                }
            }
            return result;
        }
    }
}
